package com.example.p2pinvest.util;

import android.content.Context;
import android.os.Handler;
import android.os.Process;
import android.view.View;
import android.widget.Toast;

import com.example.p2pinvest.common.MyApplication;

/**
 * @author h2tc01
 * @version 1.0.0
 * 2022/8/3
 * 处理UI相关问题的工具类
 */
public class UIUtils {
    public static Context getContext() {
        return MyApplication.context;
    }

    public static Handler getHandler() {
        return MyApplication.handler;
    }

    //返回指定colorId对应的颜色值
    public static int getColor(int colorId) {
        return getContext().getResources().getColor(colorId);
    }

    //返回指定viewId的视图
    public static View getView(int viewId) {
        return View.inflate(getContext(), viewId, null);
    }

    public static String[] getStringArr(int stringArrId) {
        return getContext().getResources().getStringArray(stringArrId);
    }

    //将dp转成px
    public static int dp2px(int dp) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);  //四舍五入
    }

    public static int px2dp(int px) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (px / density + 0.5);
    }

    /**
     * 保存runnable中的操作在主线程中执行
     *
     * @param runnable 异步方法
     */
    public static void runOnUIThread(Runnable runnable) {
        if (isInMainThread()) {
            //主线程则直接执行
            runnable.run();
        } else {
            UIUtils.getHandler().post(runnable);
        }
    }

    //判断当前线程是否为主线程
    private static boolean isInMainThread() {
        int currentThread = Process.myTid();
        return MyApplication.mainThreadId == currentThread;
    }

    public static void toast(String message,boolean isLengthLong){
        Toast.makeText(UIUtils.getContext(), message,isLengthLong? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
    }
}
